import React, { useState, useEffect } from "react";
import { Space, Button, Typography, Card, theme } from 'antd';
import { AppstoreAddOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import LinkBtn from './components/linkBtn';
import PortMap from './components/portMap';
import OrderList from './components/orderList';
import Task from './components/task';
import Warn from './components/warning';

import PortLine from './components/portCharts';
import Percent from './components/percent';
import YearBar from './components/yearCharts';

import { Responsive, WidthProvider } from "react-grid-layout";
import './index.css';
const ResponsiveReactGridLayout = WidthProvider(Responsive);


export default (props) => {
  const { token: { colorBgBase } } = theme.useToken();// 主题切换
  const [isEdit, setIsEdit] = useState(false);

  // 所有模块
  const initBlock = {
    "a": { title: '快捷入口', child: <LinkBtn /> },
    "b": { title: '待办任务', child: <Task /> },
    "c": { title: '异常提醒', child: <Warn /> },
    "d": { title: '运踪地图', child: <PortMap /> },
    "e": { title: '我的订单', child: <OrderList /> },
    "f": { title: '知识星球', child: <Percent />, maxW: 2, maxH: 6 },
    "g": { title: '业务分析', child: <YearBar /> }
  }

  // 初始化位置 待生成
  const initLayout = [
    { "w": 6, "h": 11, "x": 0, "y": 0, "i": "d" },
    { "w": 4, "h": 5, "x": 6, "y": 0, "i": "a" },
    { "w": 4, "h": 6, "x": 6, "y": 5, "i": "g" },
    { "w": 2, "h": 11, "x": 10, "y": 0, "i": "b" },
    { "w": 10, "h": 9, "x": 0, "y": 11, "i": "e" },
    { "w": 2, "h": 9, "x": 10, "y": 11, "i": "c" }
  ]


  const [layout, setLayout] = useState({ lg: JSON.parse(localStorage.getItem("WORKPLACE_LAYOUT")) || initLayout });
  const [toolbox, setToolbox] = useState([]);

  useEffect(() => {
    let tempBlock = initBlock;
    layout["lg"].forEach(element => {
      delete tempBlock[element.i];
    });

    let newBlock = [];
    Object.keys(tempBlock).forEach(element => {
      newBlock.push({ w: 2, h: 2, x: 0, y: 0, minW: initBlock[element]?.minW, minH: initBlock[element]?.minH, i: element, maxW: initBlock[element]?.maxW, maxH: initBlock[element]?.maxH })
    })
    setToolbox(newBlock)
  }, [isEdit])

  // 布局变化
  const onLayoutChange = (e) => {
    setLayout({ lg: e });
  }

  // 编辑布局
  const editLayout = () => {
    setIsEdit(true);
  }
  // 保存布局
  const saveLayout = () => {
    // todo 保存后台
    localStorage.setItem("WORKPLACE_LAYOUT", JSON.stringify(layout["lg"]));
    setIsEdit(false);
  }
  // 取消布局
  const cancelLayout = () => {
    setIsEdit(false);
    setLayout({ lg: JSON.parse(localStorage.getItem("WORKPLACE_LAYOUT")) || initLayout });
  }

  // 模块管理栏
  const ToolBox = (props) => {
    return (<Card
      bordered={false}
      bodyStyle={{ display: 'flex', flexWrap: 'nowrap', padding: '5px', }}
      >
      <Space className="toolbox">
        模块：
        {props.items.map(item => (
          <Button
            key={item.i}
            type="primary"
            onClick={() => onAddItem(item.i)}
          >
            {initBlock[item.i].title}
          </Button>
        ))}
      </Space>
      <div className="toolbox-btns">
        <Space>
          <Button size="small" shape="round" icon={<CloseOutlined />} onClick={cancelLayout} >取消</Button>
          <Button type="primary" size="small" shape="round" icon={<CheckOutlined />} onClick={saveLayout} >保存</Button>
        </Space>
      </div>
    </Card>);
  }

  // 添加模块
  const onAddItem = element => {
    setLayout({ lg: layout["lg"].concat(toolbox.filter(item => item.i == element)) });
    setToolbox(toolbox.filter(item => item.i != element));
  };
  // 删除模块
  const onDelItem = element => {
    setToolbox(toolbox.concat(layout["lg"].filter(item => item.i == element)));
    setLayout({ lg: layout["lg"].filter(item => item.i != element) });
  };

  // 模块渲染
  const generateDOM = () => {
    return layout['lg'].map((item) =>
      <div key={item.i} className={colorBgBase == '#fff' ? "" : "dark"}>
        {isEdit && <div className={"hide-button"+(colorBgBase == '#fff' ? "" : " dark")} onClick={() => onDelItem(item.i)}>&times;</div>}
        <div className="react-grid-item-content">
          {initBlock[item.i].child}
        </div>
      </div>
    );
  }

  return (
    <div style={{ height: 'calc(100vh - 100px)', minWidth: '1600px' }}>
      <div className="grid-layout-header">
      {isEdit ? <ToolBox items={toolbox} onTakeItem={onAddItem} /> : <div className="grid-layout-title"><Typography.Text>您好,Quinn</Typography.Text>
        <Button size="small" type="text" icon={<AppstoreAddOutlined />} onClick={editLayout} /></div>}
        </div>
      <ResponsiveReactGridLayout
        rowHeight={30}
        layouts={layout}
        onLayoutChange={onLayoutChange}
        compactType="horizontal"
        isDraggable={isEdit}
        isResizable={isEdit}
        allowOverlap={true}
        preventCollision={true}
      >
        {generateDOM()}
      </ResponsiveReactGridLayout>
    </div>
  )
}